<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import AddAdvertisement from "@/views/ming/addAdvertisement.vue";
import axios from "axios";

const queryParams = ref({});

const adList = ref([]);
const currentPage=ref(1)
const pageSize=ref(4)
const total=ref(0);
const loading = ref(false);
const selectedRows = ref([]);

// 查询广告列表
const getAdListData = () => {
  axios.post(`/advertisement/getAdListData/${currentPage.value}/${pageSize.value}`,queryParams.value).then(resp=>{
    adList.value=resp.data.data;
    total.value=resp.data.total;
  })
};

// 查询条件变化时触发
const handleQuery = () => {
  getAdListData();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {};
};
const visible=ref(false);
// 新增广告
const handleAdd = () => {
  // 跳转到新增页面或弹出表单
  visible.value=true;
};
const advertisement=ref({});
// 编辑广告
const handleEdit = (row) => {
  axios.get(`/advertisement/getAdvertisementById/${row.adId}`).then(resp=>{
    advertisement.value=resp.data;
    visible.value=true;
  })
};
// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
      '<strong>确定要删除这些数据吗？</strong><br><span style="color: red;">删除后无法恢复</span><br><span style="color: gray;">请问还要继续吗？</span>',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
  )
      .then(() => {
        axios.delete("/advertisement/batchDelete",selectedRows.value).then(resp=>{
          ElMessage.success(resp.data)
        }).catch(err=>{
          ElMessage.error(err.response.data);
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
};
const ids=ref([])
// 单选框变化时更新选中项
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
  ids.value = selectedRows.value.map(item=>item.adId)
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getAdListData();
};

// 分页页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getAdListData();
};

// 上线操作
const handlePublish = () => {
  axios.post("/advertisement/batchPublish",ids.value).then(resp=>{
    ElMessage.success(resp.data)
    getAdListData();
  })
};

// 下线操作
const handleOffline = () => {
  axios.post("/advertisement/batchOffline",ids.value).then(resp=>{
    ElMessage.success(resp.data)
    getAdListData();
  })
};

// 页面加载时获取广告列表
onMounted(() => {
  getAdListData();
  getAdPositions();
});
const adPositions=ref([])
const options = ref([
  {label: '上线', value: 1},
  {label: '下线', value: 0},
])
const getAdPositions =()=>{
  axios.get("/advertisement/getAdPositions").then(resp=>{
    adPositions.value=resp.data.map((item,index)=>({
      label:item.position,
      value: item.position
    }))
  })
}
const getVisible=(val)=>{
  visible.value=val;
}
const handleStatusChange =(row)=>{
  axios.put(`/advertisement/changeStatus/${row.adId}/${row.status}`).then(resp=>{
    ElMessage.success(resp.data)
  })
}
const handleDelete =(row)=>{
  ElMessageBox.confirm(
      '<strong>确定要删除这些数据吗？</strong><br><span style="color: red;">删除后无法恢复</span><br><span style="color: gray;">请问还要继续吗？</span>',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
  )
      .then(() => {
        axios.delete(`/advertisement/delete/${row.adId}`).then(resp=>{
          ElMessage.success(resp.data)
          getAdListData();
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}
const handleTop =(row)=>{
  if (row.topLevel===0){
    axios.put(`/advertisement/top/${row.adId}`).then(resp=>{
      ElMessage.success(resp.data)
      getAdListData();
    })
  }else {
    axios.put(`/advertisement/unpin/${row.adId}`).then(resp=>{
      ElMessage.success(resp.data)
      getAdListData();
    })
  }

}

</script>

<template>
    <div class="ad-management">
      <!-- 查询条件区域 -->
      <el-card class="query-card">
        <div class="query-container">
          <el-form :inline="true" :model="queryParams" label-width="80px">
            <el-form-item label="广告名称:">
              <el-input v-model="queryParams.adName" placeholder="请输入广告名称" clearable />
            </el-form-item>
            <el-form-item label="广告位置:" style="width: 200px">
              <el-select v-model="queryParams.position" placeholder="全部" style="width: 100%" clearable>
                <el-option
                    v-for="item in adPositions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上线状态:" style="width: 200px">
              <el-select v-model="queryParams.status" placeholder="全部" style="width: 100%" clearable>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>

      <!-- 操作按钮区域 -->
      <el-card class="action-card">
        <div class="action-container">
          <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length===0">删除</el-button>
          <el-button type="success" icon="Play" @click="handlePublish" :disabled="selectedRows.length===0">上线</el-button>
          <el-button type="warning" icon="Pause" @click="handleOffline" :disabled="selectedRows.length===0">下线</el-button>
        </div>
      </el-card>
      <el-alert v-if="selectedRows.length > 0" :title="`已选择${selectedRows.length}项，可以进行批量操作`" type="info" show-icon></el-alert>
      <!-- 广告列表区域 -->
      <el-card class="table-card">
        <el-table
            v-loading="loading"
            :data="adList"
            border
            @selection-change="handleSelectionChange"
        >
          <!-- 复选框列 -->
          <el-table-column type="selection" width="50" align="center" />

          <!-- 广告编号 -->
          <el-table-column label="广告编号" prop="adId" width="120" />

          <!-- 广告名称 -->
          <el-table-column label="广告名称" prop="adName" min-width="200"></el-table-column>
          <!-- 商品图片 -->
          <el-table-column label="商品图片" width="120">
            <template #default="{ row }">
              <el-image
                  :src="row.imageUrl"
                  fit="cover"
                  style="width: 80px; height: 80px"
              />
            </template>
          </el-table-column>

          <!-- 跳转地址 -->
          <el-table-column label="跳转地址" min-width="200">
            <template #default="{ row }">
              <el-link type="primary" :href="row.redirectUrl" target="_blank">{{ row.redirectUrl }}</el-link>
            </template>
          </el-table-column>

          <!-- 广告位置 -->
          <el-table-column label="广告位置" prop="position" width="180" />

          <!-- 广告时间 -->
          <el-table-column label="广告时间" width="240">
            <template #default="{ row }">
              开始时间：{{ row.startTime }}<br>
              结束时间：{{ row.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="上线/下线" width="200">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.status"
                  class="ml-2"
                  :active-value="1"
                  :inactive-value="0"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" @click="handleTop(scope.row)">{{ scope.row.topLevel===0?'置顶':'取消置顶' }}</el-button>
              <el-button type="text" @click="handleDelete(scope.row)" style="color: #ff4949">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[4, 10, 20, 40]"
            :size="'small'"
            :disabled="false"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="text-align: center; margin-top: 20px;"
        ></el-pagination>
      </el-card>
    </div>
  <addAdvertisement :visible="visible" @dialogVisible="getVisible" :advertisement="advertisement"/>
</template>

<style scoped>
.ad-management {
  padding: 20px;

  .query-card,
  .action-card,
  .table-card {
    margin-bottom: 20px;
  }

  .query-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;

    .el-form-item {
      margin-bottom: 10px;
    }
  }

  .action-container {
    display: flex;
    gap: 10px;
  }

  .link-text {
    color: #409EFF;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>